package spring.study.beanpostproessor.processor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * Created by Format on 2017/6/20.
 */
//@Component
public class SimpleDestructionAwareBeanPostProcessor implements DestructionAwareBeanPostProcessor {

    private String name = "simpleServiceForDestroy";

    @Override
    public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
        if(beanName != null && beanName.equals(name)) {
            System.err.println("DestructionAwareBeanPostProcessor postProcessBeforeDestruction: " + beanName + ", " + bean);
        }
    }

    /**
     * Determine whether the given bean instance requires destruction by this
     * post-processor.
     * <p><b>NOTE:</b> Even as a late addition, this method has been introduced on
     * {@code DestructionAwareBeanPostProcessor} itself instead of on a SmartDABPP
     * subinterface. This allows existing {@code DestructionAwareBeanPostProcessor}
     * implementations to easily provide {@code requiresDestruction} logic while
     * retaining compatibility with Spring <4.3, and it is also an easier onramp to
     * declaring {@code requiresDestruction} as a Java 8 default method in Spring 5.
     * <p>If an implementation of {@code DestructionAwareBeanPostProcessor} does
     * not provide a concrete implementation of this method, Spring's invocation
     * mechanism silently assumes a method returning {@code true} (the effective
     * default before 4.3, and the to-be-default in the Java 8 method in Spring 5).
     *
     * @param bean the bean instance to check
     * @return {@code true} if {@link #postProcessBeforeDestruction} is supposed to
     * be called for this bean instance eventually, or {@code false} if not needed
     * @since 4.3
     */
    @Override
    public boolean requiresDestruction(Object bean) {
        return false;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals(name)) {
            System.err.println("DestructionAwareBeanPostProcessor postProcessBeforeInitialization: " + beanName + ", " + bean);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals(name)) {
            System.err.println("DestructionAwareBeanPostProcessor postProcessAfterInitialization: " + beanName + ", " + bean);
        }
        return bean;
    }

}
